<?php
/**
 * Created by PhpStorm.
 * User: leishaofa
 * Date: 2017/7/9
 * Time: 15:37
 */
class MyTeamAction extends CommonAction{
    public function __construct(){
        parent::__construct();
        //import("rndChinaName",dirname(__FILE__).'/Extend/Vendor/',".class.php");
        //import("rndChinaName",dirname(__FILE__).'/Extend/Vendor/',".class.php");
        Vendor('rndChinaName','','.class.php');
    }

    /**
     * @auth:leishaofa
     * @date:204170710
     * @efect:团队任务列表
     */
    public function myTask(){
        $memberinfo=session('member_info');
        $where='where a.t_id ='.$memberinfo['t_id'];
        $where.=is_numeric($_GET['site'])?' and a.site_id ='.$_GET['site']:'';
        $where.=is_numeric($_GET['status'])?' and b.task_status ='.$_GET['status']:'';
        if($_GET['teamstatus'] != 3) {
            $where .= is_numeric($_GET['teamstatus']) ? ' and a.status =' . $_GET['teamstatus'] : ' and a.status <> 3';
        }
        $this->taskdata($where);
        $this->assign('indis',0);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:204170710
     * @efect:创建团队任务
     */
    public function myCreateTask(){
        if(IS_AJAX){
            $memberinfo=session('member_info');
            $is_account=M('user','f_',C('flashSale'))->query('select u_id from f_user where t_id='.$memberinfo['t_id'].' limit 1 ');
            if(empty($is_account)){
                $this->ajaxError("您还没有抢购账号，无法创建任务");
            }
            if(IS_POST){
                $site=is_numeric($_POST['site'])?$_POST['site']:'';
                $url=filter_var(trim($_POST['goodurl']),FILTER_VALIDATE_URL);
                $taskid=is_numeric($_POST['teskurl'])?$_POST['teskurl']:'';
                $goodsattr=$_POST['goodsattr'];
                if(!empty($site) && !empty($taskid)) {
                    $model = M('', '', C('flashSale'));
                    $where = 'where b.site_status = 1 && a.task_status = 1 && a.site_id = ' . $site . ' && a.task_id=' . $taskid . '  ';
                    $sql = "select a.task_url as url ,a.task_id as id ,a.goods_attr as attr,a.pinicBuying_types,a.goods_time  from f_task as a left join f_site as b ON a.site_id=b.site_id " . $where . " limit 1";
                    $result = $model->query($sql);
                   // if(!$result || !(strpos($result[0]['url'],$url)!== false)){
                    if(!$result){
                        parent::ajaxError("没有找到该任务");
                    }
                    $result=$result[0];
                   /* if(empty($result['attr'])){
                        parent::ajaxError("该商品规格未找到或者商品已下架");
                    }*/

                    $attr=empty($result['attr'])?'': $attr=json_decode($result['attr'],true);
                    $attrrelus=[];
                    //组装任务商品规格
                    if(!empty($goodsattr) && is_array($goodsattr)) {
                        foreach ($attr as $key => $val) {
                            foreach ($goodsattr as $k => $v) {
                                if ($key == $k) {
                                    $attrrelus[$key] = [];
                                    if (count(array_intersect($val[0], $v['keys'])) != count($v['keys'])) {
                                        parent::ajaxError("商品规格不正确");
                                        exit();
                                    }
                                    $attrrelus[$key][0] = $v['keys'];
                                    if (count(array_intersect($val[1], $v['vals'])) != count($v['vals'])) {
                                        parent::ajaxError("商品规格不正确");
                                        exit();
                                    }
                                    $attrrelus[$key][1] = $v['vals'];
                                }
                            }
                        }
                        $attrrelus=json_encode($attrrelus,JSON_UNESCAPED_UNICODE);
                    }else{
                        $attrrelus=json_encode($attr,JSON_UNESCAPED_UNICODE);
                    }
                    unset($attr,$goodsattr);
                    $querysql="select task_relid from f_task_rel where task_id =".$result['id']." &&  site_id=".$site." &&  t_id=".$memberinfo['t_id']."  limit 1";
                    $queryresult=$model->query($querysql);
                    //$rules=json_encode(array('goods_time'=>$result['goods_time'],'pinicBuyingTypes'=>$result['pinicBuying_types'],'attr'=>empty($attr)?'':$attr));

                    if(empty($queryresult)){
                        $addsql="INSERT INTO f_task_rel (task_id,t_id,rules,status,task_type,site_id) VALUES(".$result['id'].",".$memberinfo['t_id'].",'".$attrrelus."',1,2,".$site.") ";
                        $resultadd =  $model->execute($addsql);
                    }else {
                        parent::ajaxError("请先删除之前执行的任务才能新建");
                      //  $sql = "INSERT INTO f_task_rel(task_relid,rules,status) VALUES (" . $queryresult[0]['task_relid'] . ",'" . json_encode($relus, JSON_UNESCAPED_UNICODE) . "',1)ON DUPLICATE KEY UPDATE task_relid=VALUES(task_relid),rules=VALUES(rules),status=VALUES(status)";
                        //$result = $model->execute($sql);
                    }
                    if($resultadd){
                        parent::ajaxSuccess("添加成功");
                    }else{
                        parent::ajaxError("添加失败");
                    }
                }
                parent::ajaxError("添加失败");
            }
            $siteModel=M('site','f_',C('flashSale'));
            $sitesql="select site_id,site_name from f_site where site_status = 1";
            $sitedao=$siteModel->query($sitesql);
            $this->assign('sitedao',$sitedao);
            $this->display();
            exit;
        }
    }


    /**
     * @auth:leishaofa
     * @date:20170831
     * @efect:启动一个任务
    */
    public function starttask(){
        if(IS_AJAX) {
            if (is_numeric($_POST['keyid'])) {
                $memberinfo = session('member_info');
                $where = 'where t_id = ' . $memberinfo['t_id'] . ' ';
                $model = M('', '', C('flashSale'));
              /*  $sql = "select count(1) as hostnumber from f_team_host " . $where . " limit 1 ";
                $hostcount = $model->query($sql);
                if ($hostcount[0]['hostnumber'] > 0) {*/
                    $where .= ' and task_relid = ' . trim($_POST['keyid']);
                    $sql = "UPDATE f_task_rel SET status = '4' " . $where . " ";
                    $result = $model->execute($sql);
                    if ($result) {
                        $this->ajaxSuccess("任务已启动");
                    } else {
                        $this->ajaxError("任务启动失败");
                    }
               /* }else {
                        $this->ajaxError("你还没有可用的主机");
                }*/
            }else{
                $this->ajaxError("该任务不存在");
            }
        }
    }

    /**
     * @auth:leishaofa
     * @date:20170928
     * @efect:查看注册任务
    */
    public function userTask(){
        $memberinfo=session('member_info');
        $where='where a.t_id ='.$memberinfo['t_id'];
        $this->taskdata($where,1);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:20170928
     * @efect:查看定时任务
    */
    public function timeTask(){
        $memberinfo=session('member_info');
        $where='where a.t_id ='.$memberinfo['t_id'];
        $this->taskdata($where,3);
        $this->display();
    }


    /**
     * @auth:leishaofa
     * @date:20170710
     * @efect:查询任务
     */
    public function searchtask(){
        if(IS_AJAX){
            $type=is_numeric($_POST['tyep'])?$_POST['tyep']:'';
            if(empty($type)){
                parent::ajaxError("请选择平台");
            }
           /* $url= filter_var(trim($_POST['goodsurl']), FILTER_VALIDATE_URL);
            if(!$url){
                parent::ajaxError("请输入正确的商品链接");
            }*/
            $model=M('','',C('flashSale'));
            //$where='where b.site_status = 1 && a.task_status = 1 && a.site_id = '.$type.' && a.task_url like "'.$url.'%"';
            $where='where b.site_status = 1 && a.task_status = 1 && a.site_id = '.$type.' ';
            $sql="select a.task_url as url ,a.task_id as id ,a.goods_attr as attr  from f_task as a left join f_site as b ON a.site_id=b.site_id " .$where." order by a.task_id desc limit 50";
            $listdata = $model->query($sql);
            if(is_array($listdata) && !empty($listdata)) {
                $listdata = array_map(function ($val) {
                    if (!empty($val['attr'])) {
                        $allattr = json_decode($val['attr'], true);
                        //循环商品属性
                        $val['attr'] = array_map(function ($v) {
                            return array_combine($v[1], $v[0]);
                        }, $allattr);
                        return $val;
                    } else {
                        return $val;
                    }
                }, $listdata);
                parent::ajaxSuccess("搜索成功",$listdata);
            }
            parent::ajaxError("查询无结果");
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170710
     * @efect:团队用户
     */
    public function accountPanic(){

        $model = M('', '', C('flashSale'));
        $memberinfo = session('member_info');
        $where='where t_id = '.$memberinfo['t_id'].' ';
        /* $where.=is_numeric($_GET['site'])?'a.site_id ='.$_GET['site']:'';
         $where.=is_numeric($_GET['status'])?'b.task_status ='.$_GET['status']:'';
         $where.=is_numeric($_GET['teamstatus'])?'a.status ='.$_GET['teamstatus']:'';
         $where.=empty(trim($_GET['teamname']))?'':'d.t_name linke "%'.htmlspecialchars($_GET['teamname']).'"';
         $where=empty(trim($where))?'':' where '.$where;*/
        if(IS_AJAX){
            $page=is_numeric($_GET['p'])?$_GET['p']:'';
            if(empty($page)){
                parent::ajaxError("页码错误");
            }
            $startnumber=($page-1)*C('PAGENUMBER');
            $sqlcount="select group_concat(b.u_site_status) as u_site_status, group_concat(b.site_id) as site_id,group_concat(b.u_site_task_status) as u_site_task_status,a.* from (select * from f_user " . $where . " ORDER BY u_id DESC, create_time DESC LIMIT ".$startnumber." , ".C('PAGENUMBER').") as a LEFT JOIN f_user_rel as b on a.u_id=b.u_id GROUP BY a.u_id";
            //$sqlcount = "select a.*,b.t_name as teamName,group_concat(c.u_site_status),group_concat(c.site_id) from f_user as a left join f_team as b on a.t_id=b.t_id left join f_user_rel as c on c.u_id=a.u_id " . $where . " order by u_id desc, create_time desc group by a.u_id limit ".$startnumber." , ".C('PAGENUMBER')." ";
            $result = $model->query($sqlcount);
           // print_r($result);
            $result=array_map(function($v) use ($memberinfo) {
                $v['teamName']=$memberinfo['t_name'];
                $v['siteid']=empty($v['site_id'])?'':explode(',',$v['site_id']);
                $v['sitestatus']=empty($v['u_site_status'])?'':explode(',',$v['u_site_status']);
                $v['u_site_task_status']=empty($v['u_site_task_status'])?'':explode(',',$v['u_site_task_status']);
                $v['u_field']=json_decode($v['u_field'],true);
                $v['u_address']= $v['u_field']['addressremark']['country'].$v['u_field']['addressremark']['province'].$v['u_field']['addressremark']['city'].$v['u_field']['addressremark']['district'].$v['u_address'];
                $v['u_field']='';
                return $v;
            },$result);
            if($result){
                $this->ajaxSuccess("成功",$result);
            }else{
                $this->ajaxError("失败");
            }
            exit;
        }
        //站点
        $sitesql = "select site_id as id,site_name as name from f_site where site_status = 1";
        $sitedao = $model->query($sitesql);
        $this->assign('sitelist',$sitedao);
        $siteModel=M('user','f_',C('flashSale'));
        //总数
        $sqlcount = "select count(*) as counts from f_user " . $where . " ";
        $resultcount = $model->query($sqlcount);
        //账号数量限制
        $resultxountuser=  M('user', 'f_', C('flashSale'))->query('select count(1) as usercount from f_user where t_id='.$memberinfo['t_id'].' ');
        $this->assign('isdisable',$resultxountuser[0]['useracount']>=C('MaxPanicBuyingAccount')?0:1);

        //页面几个权限
        import("ORG.Util.Auth");
        $auth=new Auth();
        $url='MyTeam/accountProduce';
        $resultproduce = $auth->check($url, $memberinfo['m_id']);
        $url='MyTeam/accountRegister';
        $resultregister = $auth->check($url, $memberinfo['m_id']);
        $url='MyTeam/unlock';
        $resultunlock = $auth->check($url, $memberinfo['m_id']);
        $this->assign('accountPanicAuth',['produce'=>$resultproduce,'register'=>$resultregister,'unlock'=>$resultunlock]);
        $this->assign('page',ceil($resultcount[0]['counts']/C('PAGENUMBER')));
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:204170711
     * @efect:excel导入账号批量生产用户地址信息
     */
    public function accountExcelImport(){
        if(IS_AJAX){
            $memberinfo = session('member_info');

            if (!empty($_POST) && is_array(json_decode($_POST['data'], true)) && !empty(json_decode($_POST['data'], true))) {
                $resultxountuser=  M('user', 'f_', C('flashSale'))->query('select count(1) as usercount from f_user where t_id='.$memberinfo['t_id'].' ');
                if($resultxountuser[0]['useracount']>=C('MaxPanicBuyingAccount')){
                    $this->ajaxError("您最多只能添加".C('MaxPanicBuyingAccount')."抢购账号");
                }
                if(empty($memberinfo['defaultAccountPwd'])){
                    $this->ajaxError("请去系统设置抢购账号密码");
                }
                //值接受过滤
                $postdata['userdefaultpwd']=preg_match("/^[A-Za-z0-9]+$/", trim($_POST['userdefaultpwd']))>0 && strlen(trim($_POST['userdefaultpwd']))>6?trim($_POST['userdefaultpwd']):'';
                if(empty($postdata['userdefaultpwd'])){
                    $this->ajaxError("密码为大小写字母数字组合");
                }
                $minage=is_numeric($_POST['agestarttime'])?trim($_POST['agestarttime']):18;
                $maxage=is_numeric($_POST['ageendtime'])?trim($_POST['ageendtime']):60;
                if($minage<18 || $maxage>60){
                    $this->ajaxError("年龄范围不正确");
                }else if($maxage<$minage){
                    $this->ajaxError("最大年龄必须大于最小年龄");
                }
               $postdata['agestarttime']=date('Y-m-d',strtotime('-'.$minage.' year'));
               $postdata['ageendtime']=date('Y-m-d',strtotime('-'.$maxage.' year'));
                $postdata['gaodegps']=is_array(explode(",",$_POST['pgsmap']))?explode(",",$_POST['pgsmap']):'';
                $postdata['quankm']=1;
                $postdata['addresscode']=is_numeric($_POST['addresscode'])?trim($_POST['addresscode']):'';
                $postdata['featurs']=htmlspecialchars(trim($_POST['userfeaturs']));
                $postdata['siteid']=array_filter(array_keys($_POST['sitetype']),'is_numeric');
                $postdata['exceltype']=is_numeric($_POST['exceltype'])?$_POST['exceltype']:'';

                $postdata['siteid']=$postdata['siteid'];
                if(empty($postdata['siteid']) || empty($postdata['exceltype'])){
                    $this->ajaxError("表格类型未选中或者数据站点未选中");
                }
                $exceldata =json_decode($_POST['data'], true);
                if (!empty($exceldata[0])) {
                    /**excel过滤数据
                     * $postdata['exceltype'] 1：excel只有邮箱 2：只有手机号  3：手机号邮箱都有
                     * 验证放到每个里面故判断验证只会验证满足当前条件的数据
                     */
                    $Abnormal = 0;//统计excel数据错误条数
                    foreach ($exceldata as $key => $val) {
                        if($postdata['exceltype'] ==1){
                            $ramilstatus = filter_var($val['email'], FILTER_VALIDATE_EMAIL);
                            if ($ramilstatus) {
                                $exceldata[$key]['telephone']= C('MODELPONE')[array_rand( C('MODELPONE'))].mt_rand(1000,9999).mt_rand(1000,9999);
                            }
                            else{
                                unset($exceldata[$key]);
                                $Abnormal++;
                            }
                        }/*elseif ($postdata['exceltype'] ==2){
                            $ponestatus = preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $val['telpone']);
                            if ($ponestatus) {
                                $exceldata[$key]['eamil']='';//C('EAMILSERVICES')[array_rand(C('EAMILSERVICES'),1)];
                            }
                            else{
                                unset($exceldata[$key]);
                                $Abnormal++;
                            }
                        }*/elseif ($postdata['exceltype'] ==3){
                            $ramilstatus = filter_var($val['email'], FILTER_VALIDATE_EMAIL);
                            $ponestatus = preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $val['telephone']);
                            if (!$ponestatus || !$ramilstatus) {
                                unset($exceldata[$key]);
                                $Abnormal++;
                            }
                        }
                    }
                    $countuser = count($exceldata);//有效筛选数据条数
                    $exceldata = array_filter($exceldata);//excel表格数据
                    if(!is_array($exceldata) || empty($exceldata) || $countuser<1){
                        $this->ajaxError("excel数据为空，数据格式错误".$Abnormal."条数据");
                    }
                    /**
                     * 超过系统设置单次导入最大数据截取
                     */
                    if((C('MaxPanicBuyingAccount')-$resultxountuser[0]['useracount'])<$countuser){
                        $offindex=$countuser-(C('MaxPanicBuyingAccount')-$resultxountuser[0]['useracount']);
                        array_splice($exceldata,$offindex-1,C('MaxPanicBuyingAccount')-$resultxountuser[0]['useracount']-1);
                    }

                    //gps坐标转换
                    if(!$postdata['gaodegps'][0] || !$postdata['gaodegps'][1]){
                        $this->ajaxError("请点击获取收货地址以便于确认位置");
                    }
                    //高德坐标转换百度坐标
                    $geodeexbaidu=bd_encrypt($postdata['gaodegps'][0],$postdata['gaodegps'][1]);
                    //获取坐标地址信息
                    $address=json_decode($this->getbaiduaddress($geodeexbaidu['bd_lat'],$geodeexbaidu['bd_lon']),true);
                    $address=$address['result'];
                    $u_city['country']=$address['addressComponent']['country'];
                    $u_city['province']=$address['addressComponent']['province'];
                    $u_city['city']=$address['addressComponent']['city'];
                    $u_city['district']=$address['addressComponent']['district'];
                    $u_city['street']=$address['addressComponent']['street'];
                   //$u_city['adcode']=$address['addressComponent']['adcode'];
                    //$u_city['formatted_address']=$address['formatted_address'];
                    //$u_city['sematic_description']=$address['sematic_description'];
                    $postdata['addresscode']=$u_city['adcode']?$u_city['adcode']:$_POST['addresscode'];
                    $insertvalues = '';
                    $remark = json_encode(['addressremark' => $u_city], JSON_UNESCAPED_UNICODE);
                    //第一次poi百度地址
                    $searchkey=C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)];
                    $string=$geodeexbaidu['bd_lon'].",".$geodeexbaidu['bd_lat'];
                    $searchpage=0;//搜索页数
                    $resultpoicoordinate=$this->extendsbaidu($string,$postdata['quankm']);//更具坐标绘制矩形
                    $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);//
                    $oneadresstotle=0;//计数查询一次返回总数递减为0新赋值一个$searchkey且不能与当前相同;
                    $cmulativeNumber=0;//加到20条请求下一页
                    $oneadresstotle=$resultaddressdata['total'];
                    if($resultaddressdata['status']==0){
                        $addressdata=$resultaddressdata['results'];//地址数据
                    }else{
                        $this->ajaxError("定位地址参数出错");
                    }
                    $pinyin=new Overtrue\Pinyin\Pinyin();
                    foreach ($exceldata as $v) {
                        if(!isset($addressdata[$cmulativeNumber])){
                            //请求下一页地址数据
                            $cmulativeNumber=0;
                            $searchpage++;
                            $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);
                            $addressdata=$resultaddressdata['results'];
                            $oneadresstotle=$resultaddressdata['total'];
                            //地址数据为空或者总和为0重新赋值一个搜索词
                            if((20*$searchpage+$cmulativeNumber+1)>=$oneadresstotle || empty($addressdata) || $oneadresstotle==0){
                                $searchpage=0;//重置累计分页
                                $searchkeycacahe=C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)];//重置搜索词
                                $searchkey=$searchkeycacahe==$searchkey?C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)]:$searchkeycacahe;
                                $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);//请求新的地址数据
                                $addressdata=$resultaddressdata['results'];//地址数据
                                $oneadresstotle=$resultaddressdata['total'];
                            }
                        }
                       // print_r($addressdata[$cmulativeNumber]);
                        $useraddress=str_replace(array($u_city['country'],$u_city['province'],$u_city['city'], $u_city['district'],$u_city['street'],$addressdata[$cmulativeNumber]['name']), array('','','', '','',''), $addressdata[$cmulativeNumber]['address']);
                        if(empty($useraddress)) {
                            $useraddress=$u_city['street'].$addressdata[$cmulativeNumber]['name'];
                        }else{
                            $useraddress =preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9-]#u','',$useraddress);
                        }
                        $userinfo = $this->createinfo($postdata['agestarttime'],$postdata['ageendtime']);
                        $info['username']=$cachedata=implode($userinfo['firstname']);
                        if(!empty($v['email']) && !empty($v['telephone']) && !empty($addressdata[$cmulativeNumber]['name'])) {
                            if (empty($insertvalues)) {
                                $insertvalues = "(" . $memberinfo['t_id'] . ",'" . $v['email'] . "','" . $postdata['userdefaultpwd'] . "','" . $v['telephone'] . "','" . $userinfo['birthday'] . "','" .  implode('',$pinyin->name($userinfo['firstname'])) . "','" . $remark . "', '" . $userinfo['firstname'] . "','" . $u_city['province'] . "','" . $postdata['addresscode'] . "','" . $useraddress . $postdata['featurs'] . "','1')";
                            } else {
                                $insertvalues .= ",(" . $memberinfo['t_id'] . ",'" . $v['email'] . "','" . $postdata['userdefaultpwd'] . "','" . $v['telephone'] . "','" . $userinfo['birthday'] . "','" . implode('',$pinyin->name($userinfo['firstname'])) . "','" . $remark . "','" . $userinfo['firstname'] . "','" . $u_city['province'] . "','" . $postdata['addresscode'] . "','" . $useraddress . $postdata['featurs'] . "','1')";
                            }
                        }
                        $cmulativeNumber++;
                    }
                    unset($exceldata);
                    $insertsql = "insert into f_user (t_id,u_eamil,u_pwd,mobile,birthday,u_name,u_field,firstname,u_city,u_addresscode,u_address,u_status) values " . $insertvalues . "; ";
                    $usermodel = M('', '', C('flashSale'));
                    $usermodel->startTrans();
                    $resultcount = $usermodel->execute($insertsql);
                    (int)$startuid=$usermodel->getLastInsID();
                    if($resultcount>0) {
                        $imax=$startuid+$resultcount;
                        for ($i=$startuid;$i < $imax;$i++){
                            foreach ( $postdata['siteid'] as $kvrel) {
                                if (!isset($userrelvalues)) {
                                    $userrelvalues = "(" . $i . ",'" . $kvrel . "','1','1')";
                                } else {
                                    $userrelvalues .= ",(" . $i . ",'" . $kvrel . "','1','1')";
                                }
                            }
                        }
                        $insertrelsql = "insert into f_user_rel (u_id,site_id,u_site_status,u_site_task_status) values " . $userrelvalues . "; ";
                        if($usermodel->execute($insertrelsql)){
                            $string = "成功导入" . $resultcount . "个用户,数据错误有" . $Abnormal . "个用户,失败了" . ($countuser - $resultcount) . "个用户";
                            $usermodel->commit();
                            $this->ajaxSuccess($string);
                        }else{
                            $string = "导入失败可能有账户已经注册或者数据为空，数据错误有" . $Abnormal . "个用户,失败了" . ($countuser - $Abnormal) . "个用户";
                            $usermodel->rollback();
                            $this->ajaxError($string);
                        }

                    }else{
                        $usermodel->rollback();
                        $string = "导入失败可能有账户已经注册或者数据为空，数据错误有" . $Abnormal . "个用户,失败了" . ($countuser - $resultcount) . "个用户";
                        $this->ajaxError($string);
                    }
                } else {
                    $this->ajaxError("excel数据格式不正确,无法写入");
                }
            }
            $Model = M('','',C('flashSale'));
            $sql="select site_name,site_id from f_site where site_status=1 ";
            $resultsite=$Model->query($sql);
            $this->assign('sitedao',$resultsite);
            $teamsql="select * from f_team where t_id='".$memberinfo['t_id']."' ";
            $resulttean=$Model->query($teamsql);
            $resulttean[0]['adressmindate'] = floor((time()-strtotime($resulttean[0]['adressmindate']))/86400/360);
            $resulttean[0]['adressmaxdate'] = floor((time()-strtotime($resulttean[0]['adressmaxdate']))/86400/360);
            $this->assign('team_info',$resulttean[0]);
            $this->display();
            exit;
        }
        echo "非法请求";


    }

    /**
     * @auth:leishaofa
     * @date:2017-07-12
     * @efect:jsscript高德地图api定位
     */
    public function baidumap(){
        $this->assign('geokey',C('GEODEAK'));
        $this->display('baidugpsmap');
    }
    /**
     * @auth:leishaofa
     * @date:2017-07-13
     * @efect:随机生成用户信息
     */
    private function createinfo($start_time,$end_time){
        $info='';
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $info['birthday']=date('Y-m-d', mt_rand($end_time,$start_time));
        $info['sex']=rand(1,2);//1男 2：女
        $name_obj = new rndChinaName();
        $name = $name_obj->getName();
        $info['firstname']=$name;
        return $info;

    }

    /**
     * @auth:leishaofa
     * @date:2017-07-13
     * @efect:发布注册任务
     */
    public function accountRegister(){
        if(IS_AJAX) {
            $memberinfo=session('member_info');
            $model = M('', '', C('flashSale'));;
            if (IS_POST && !empty($_POST['site'])) {
                $siteid=implode(array_keys($_POST['site']),',');
               // $siteid=is_numeric($_POST['site'])?$_POST['site']:0;
                if(empty($siteid)){
                    $this->ajaxError("请选择平台");
                }
                $querysql="select task_relid from f_task_rel where t_id = '".$memberinfo['t_id']."' and task_type = 1";
                $queryresult =  $model->query($querysql);
               if(empty($queryresult)){
                    $addsql="INSERT INTO f_task_rel (task_id,t_id,rules,status,task_type,site_id) VALUES(0,".$memberinfo['t_id'].",'".$siteid."',4,1,0) ";
                    $addresult =  $model->execute($addsql);
                    if($addresult){
                        parent::ajaxSuccess("成功");
                    }else{
                        parent::ajaxError("失败");
                    }
                }else{
                    $this->ajaxError("已经存在注册任务，等待线程执行脚本调用");
                }
             /*   $postData = array('pythontype' => 'getSize', 'task_url' => $val['task_url'], 'site_id' => $val['site_id']);
                // $url = "";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
                curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                //print_r(curl_error($ch));
                $output = curl_exec($ch);
                curl_close($ch);
                if (preg_match('/^\xEF\xBB\xBF/', $output)) {
                    $output = substr($output, 3);
                }
                $output = json_decode(trim($output), true);
                $array = $output['data'];
                $ret = $output['status'];
                $val['shellstatus'] = $ret;//执行状态
                $val['goodsattr'] = $dao['goods_attr'] = json_encode(json_decode($array[0], true));*/
            }


             $sitesql = "select site_id,site_name from f_site where site_status = 1";
            $sitedao = $model->query($sitesql);
            $this->assign('sitedao', $sitedao);
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-4
     * @efect:删除团队任务
     */
    public function deletaskrel(){
        if(IS_AJAX){
            $id=is_numeric($_POST['keyid'])?$_POST['keyid']:0;
            $memberinfo=session('member_info');
            if(empty($id)){
                parent::ajaxError("参数不存在");
            }

           /* elseif(!empty($memberinfo['m_type'])){
                parent::ajaxError("没有权限");
            }*/
            $sql="delete from f_task_rel where task_relid=".$id."  and t_id = ". $memberinfo['t_id']."  ";
           // $sql="update f_task_rel set status=3 where task_relid=".$id."  and t_id = ". $memberinfo['t_id']." ";
            $taskmodel=M('task_rel','f_',C('flashSale'));
            if($taskmodel->execute($sql)){
                parent::ajaxSuccess("删除成功");
            }else{
                parent::ajaxError("删除失败");
            }
            exit;
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-24
     * @efect:终止正在运行的脚本
     */
    public function stopTaskrel(){
        if(IS_AJAX){
            $id=is_numeric($_POST['keyid'])?$_POST['keyid']:0;
            $memberinfo=session('member_info');
            if(empty($id)){
                parent::ajaxError("参数不存在");
            }
            $sql="update f_task_rel set status=2 where task_relid=".$id." and t_id = ". $memberinfo['t_id']." ";
            $taskmodel=M('task_rel','f_',C('flashSale'));
            if($taskmodel->execute($sql)){
                parent::ajaxSuccess("任务已终止");
            }else{
                parent::ajaxError("任务终止失败");
            }
            exit;
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-25
     * @efect:团队成员列表
     */
    public function staff(){
        $memberinfo=session('member_info');
        //取分页数据
        $page=is_numeric($_GET['p'])?$_GET['p']:'';
        $model=M('','',C('flashSale'));
        $where=' where a.t_id ='.$memberinfo['t_id'].' and  b.m_type = 2 ';
        if($page) {
            $startnumber=($page-1)*C('PAGENUMBER');
            $listdata = $model->query(" select b.m_id as id ,b.m_name as name,b.m_email as email,b.m_status as is_status,b.m_updatetime as times, b.m_ip as ip  from f_member_rel as a left join f_member as b ON a.m_id=b.m_id  ".$where." limit ".$startnumber.",".C('PAGENUMBER')." ");

            if (is_array($listdata) && !empty($listdata)) {
                return $this->ajaxReturn(array('code' => 101, 'msg' => "成功", 'data' => $listdata));
            } else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有数据", 'data' => $model->getLastSql()));
            }
            exit;
        }

        $resultcount=$model->query('select COUNT(1) as countnum from f_member_rel as a left join f_member as b on a.m_id=b.m_id  '.$where);

        $this->assign('adddisable',$resultcount[0]['countnum']>=C('MaxTeamUser')?0:1);

        $this->assign('page',ceil($resultcount[0]['countnum']/C('PAGENUMBER')));
        C('TOKEN_ON',false);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-25
     * @efect:添加团队成员列表
     */
    public function staffAdd(){
        $id=is_numeric($_GET['id'])?$_GET['id']:'';
        $memberinfo=$_SESSION['member_info'];
        $model = M('','',C('flashSale'));
        $where=' where a.t_id ='.$memberinfo['t_id'].' and  b.m_type = 2 ';
        $resultcount=$model->query('select COUNT(1) as countnum from f_member_rel as a left join f_member as b on a.m_id=b.m_id  '.$where);
        if($resultcount[0]['countnum']>=C('MaxTeamUser')){
            $this->ajaxError("您只能添加".C('MaxTeamUser')."团队成员");
        }

        $where=' where b.t_id ='.$memberinfo['t_id'];
        if(!empty($id)){
            $where.=' and a.m_id='.$id;
            //查询修改数据库
            $findsql="select a.*,c.* from f_member as a left join f_member_rel as b on b.m_id= a.m_id LEFT join f_team as c on b.t_id=c.t_id  ".$where." limit 1";
            $update=$model->query($findsql);
        }
        if(IS_POST){
            if (!$model->autoCheckToken($_POST)){
                // 令牌验证错误
                parent::ajaxError('表单已提交过！请关闭窗口重新填写！');
            }
            $userstatus=isset($_POST['usersattus'])?1:2;
            if($id){
                if(empty($memberinfo['defaultpwd'])){
                    parent::ajaxError('请填写系统设置信息');
                }
                //修改
                $pwdreset=isset($_POST['pwdreset'])?md5(md5($memberinfo['defaultpwd']) . C('RAND_PASSWORD')):$update[0]['m_pwd'];
                $sql1="INSERT INTO f_member (m_id,m_status,m_name,m_pwd) VALUES(".$id."," . $userstatus . ",'" .$update[0]['m_name'] . "','" .$pwdreset . "') ON DUPLICATE KEY UPDATE m_id=VALUES(m_id),m_status=VALUES(m_status),m_name=VALUES(m_name),m_pwd=VALUES(m_pwd) ";
                $result = M('member', 'f_', C('flashSale'))->execute($sql1);

                if($result){
                    $this->ajaxSuccess('修改成功！');
                }else{
                    $this->ajaxError('修改失败');
                }
            }else {
                //添加
                $email = filter_var($_POST['email'],FILTER_VALIDATE_EMAIL);
                $password = htmlspecialchars($_POST['password']);
                $regPwd =  htmlspecialchars($_POST['regPwd']);
                $data = M('member', 'f_', C('flashSale'))->query("select m_email from f_member where m_email ='" . $email . "' limit 1");
                if (!empty($data)) {
                    $this->ajaxError('该邮箱已经禁止注册！');
                }
                if ($password != $regPwd) {
                    $this->ajaxError('两次密码输入必须一致！');
                }
                if (strlen($password) < 6 || strlen($password) > 64) {
                    $this->ajaxError('密码长度太短或者密码太长');
                }
                $name = $email;
                $model->startTrans();
                $result = M('member', 'f_', C('flashSale'))->execute("INSERT INTO f_member (m_name,m_email,m_pwd,m_status,m_type) VALUES('" . $name . "','" . $email . "','" . md5(md5($password) . C('RAND_PASSWORD')) . "',".$userstatus.",2) ");
                $resultid = M('member', 'f_', C('flashSale'))->getLastInsId();
                $result2 = M('member_rel', 'f_', C('flashSale'))->execute("INSERT INTO f_member_rel (m_id,t_id,group_id) VALUES(" . $resultid . "," . $memberinfo['t_id'] . ",3)");
                if ($result && $result2) {
                    $model->commit();
                    $this->ajaxSuccess('新增成功！');
                } else {
                    $model->rollback();
                    $this->ajaxError('新增失败！');
                }
            }
        }

        if(!empty($id)){
            $this->assign('updateone',$update[0]);
        }
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:204170710
     * @efect:正在执行中任务列表
     */
    public function inExecution(){
        $memberinfo=session('member_info');
        $model = M('', '', C('flashSale'));
        $where='where a.t_id ='.$memberinfo['t_id'];
        $where.=is_numeric($_GET['site'])?' and a.site_id ='.$_GET['site']:'';
        $where.=is_numeric($_GET['status'])?' and b.task_status ='.$_GET['status']:'';
        $where .= ' and a.status =4';
        $this->taskdata($where);
        $this->assign('indis',1);
        $this->display('myTask');
    }

    /**
     * @auth:leishaofa
     * @date:204170710
     * @efect:已结束任务列表
     */
    public function endTaskrel(){
        $memberinfo=session('member_info');

        $where='where a.t_id ='.$memberinfo['t_id'];
        $where.=is_numeric($_GET['site'])?' and a.site_id ='.$_GET['site']:'';
        $where.=is_numeric($_GET['status'])?' and b.task_status ='.$_GET['status']:'';
        $where .= ' and a.status =2';

        $this->taskdata($where);
        $this->assign('indis',2);
        $this->display('myTask');
    }

    private function  taskdata($where,$task_type=2){
        $where.=' and task_type = '.$task_type;
        $model = M('', '', C('flashSale'));
        if(IS_AJAX){
            $page=is_numeric($_GET['p'])?$_GET['p']:0;
            if(empty($page)){
                $this->ajaxError("页码错误");
            }
            if($_GET['teamstatus'] == 3){
                $this->ajaxError("参数错误");
            }
            $startnumber=($page-1)*C('PAGENUMBER');
            $sqlcount = "select a.*,b.task_status,b.task_url,b.goods_time,b.pinicBuying_types,c.site_name,c.site_status,d.t_name from f_task_rel as a left join f_task as b ON a.task_id=b.task_id and a.site_id=b.site_id left join f_site as c on a.site_id=c.site_id  LEFT JOIN f_team AS d ON a.t_id = d.t_id " . $where . " limit ".$startnumber." , ".C('PAGENUMBER')." ";

            //print_r($sqlcount);
            $result = $model->query($sqlcount);
            $result=array_map(function($val){
                $val['goods_time']=date('Y-m-d H:i:s',$val['goods_time']);
                return $val;
            },$result);
            if($result){
                $this->ajaxSuccess("成功",$result);
            }else{
                $this->ajaxError("失败");
            }
            exit;
        }
        $siteModel=M('site','f_',C('flashSale'));
        $sitesql="select site_id,site_name,site_status from f_site";
        $sitedao=$siteModel->query($sitesql);
        $this->assign('sitedao',$sitedao);
        $sqlcount = "select count(*) as counts from f_task_rel as a left join f_task as b ON a.task_id=b.task_id and a.site_id=b.site_id left join f_site as c on a.site_id=c.site_id " . $where . " ";
        $resultcount = $model->query($sqlcount);
        $this->assign('page',ceil($resultcount[0]['counts']/C('PAGENUMBER')));
    }

    /**
     * @efect:批量生产用户
     * @auth:leishaofa
     * @date:20170914
    */
    public function accountProduce(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            if (!empty($_POST)) {

                $resultxountuser=  M('user', 'f_', C('flashSale'))->query('select count(1) as usercount from f_user where t_id='.$memberinfo['t_id'].' ');
                if($resultxountuser[0]['useracount']>=C('MaxPanicBuyingAccount')){
                    $this->ajaxError("您最多只能添加".C('MaxPanicBuyingAccount')."抢购账号");
                }
                if(empty($memberinfo['defaultAccountPwd'])){
                    $this->ajaxError("请去系统设置抢购账号密码");
                }
                //值接受过滤
                $postdata['userdefaultpwd']=preg_match("/^[A-Za-z0-9]+$/", trim($_POST['userdefaultpwd']))>0 && strlen(trim($_POST['userdefaultpwd']))>6?trim($_POST['userdefaultpwd']):'';
                if(empty($postdata['userdefaultpwd'])){
                    $this->ajaxError("密码为大小写字母数字组合");
                }
                $minage=is_numeric($_POST['agestarttime'])?trim($_POST['agestarttime']):18;
                $maxage=is_numeric($_POST['ageendtime'])?trim($_POST['ageendtime']):60;
                if($minage<18 || $maxage>60){
                    $this->ajaxError("年龄范围不正确");
                }else if($maxage<$minage){
                    $this->ajaxError("最大年龄必须大于最小年龄");
                }
                $postdata['agestarttime']=date('Y-m-d',strtotime('-'.$minage.' year'));
                $postdata['ageendtime']=date('Y-m-d',strtotime('-'.$maxage.' year'));
                $postdata['gaodegps']=is_array(explode(",",$_POST['pgsmap']))?explode(",",$_POST['pgsmap']):'';
                $postdata['quankm']=1;
                $postdata['addresscode']=is_numeric($_POST['addresscode'])?trim($_POST['addresscode']):'';
                $postdata['featurs']=htmlspecialchars(trim($_POST['userfeaturs']));
                $postdata['siteid']=array_filter(array_keys($_POST['sitetype']),'is_numeric');

                //值接受过滤
                $postdata['maxaccountnum']=is_numeric($_POST['maxaccountnum'])?$_POST['maxaccountnum']:0;
                if($postdata['maxaccountnum']>500 || $postdata['maxaccountnum']<0 || !floor($postdata['maxaccountnum'])==$postdata['maxaccountnum']){
                    $this->ajaxError("为了导入性能单次导入最多500用户");
                }
                if(!$postdata['gaodegps'][0] || !$postdata['gaodegps'][1]){
                    $this->ajaxError("请点击获取收货地址以便于确认位置");
                }
                $ponedata=$this->randomPone($postdata['maxaccountnum']);//生成手机号
                //高德坐标转换百度坐标
                $geodeexbaidu=bd_encrypt($postdata['gaodegps'][0],$postdata['gaodegps'][1]);
                //获取坐标地址信息
                $address=json_decode($this->getbaiduaddress($geodeexbaidu['bd_lat'],$geodeexbaidu['bd_lon']),true);
                $address=$address['result'];
                $u_city['country']=$address['addressComponent']['country'];
                $u_city['province']=$address['addressComponent']['province'];
                $u_city['city']=$address['addressComponent']['city'];
                $u_city['district']=$address['addressComponent']['district'];
                $u_city['street']=$address['addressComponent']['street'];
                $postdata['addresscode']=$u_city['adcode']?$u_city['adcode']:$_POST['addresscode'];
                $insertvalues = '';
                $remark = json_encode(['addressremark' => $u_city], JSON_UNESCAPED_UNICODE);
                //第一次poi百度地址
                $searchkey=C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)];
                $string=$geodeexbaidu['bd_lon'].",".$geodeexbaidu['bd_lat'];
                $searchpage=0;//搜索页数
                $resultpoicoordinate=$this->extendsbaidu($string,$postdata['quankm']);//更具坐标绘制矩形
                $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);//
                $oneadresstotle=0;//计数查询一次返回总数递减为0新赋值一个$searchkey且不能与当前相同;
                $cmulativeNumber=0;//加到20条请求下一页
                $oneadresstotle=$resultaddressdata['total'];
                if($resultaddressdata['status']==0){
                    $addressdata=$resultaddressdata['results'];//地址数据
                }else{
                    $this->ajaxError("定位地址参数出错");
                }
                $addresslist=[];
                $insertvalues='';
                $name_obj = new rndChinaName();
                $pinyin=new Overtrue\Pinyin\Pinyin();
                foreach ($ponedata as $k=>$v){
                    if(!isset($addressdata[$cmulativeNumber])){
                        //请求下一页地址数据
                        $cmulativeNumber=0;
                        $searchpage++;
                        $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);
                        $addressdata=$resultaddressdata['results'];
                        $oneadresstotle=$resultaddressdata['total'];
                        //地址数据为空或者总和为0重新赋值一个搜索词
                        if((20*$searchpage+$cmulativeNumber+1)>=$oneadresstotle || empty($addressdata) || $oneadresstotle==0){
                            $searchpage=0;//重置累计分页
                            $searchkeycacahe=C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)];//重置搜索词
                            $searchkey=$searchkeycacahe==$searchkey?C('BAIDUSEARCHKEY')[array_rand(C('BAIDUSEARCHKEY'),1)]:$searchkeycacahe;
                            $resultaddressdata=$this->getbaidupoi($resultpoicoordinate,$searchkey,$searchpage);//请求新的地址数据
                            $addressdata=$resultaddressdata['results'];//地址数据
                            $oneadresstotle=$resultaddressdata['total'];
                        }
                    }
                    $useraddress=str_replace(array($u_city['country'],$u_city['province'],$u_city['city'], $u_city['district'],$u_city['street'],$addressdata[$cmulativeNumber]['name']), array('','','', '','',''), $addressdata[$cmulativeNumber]['address']);
                    if(empty($useraddress)) {
                        $useraddress=$u_city['street'].$addressdata[$cmulativeNumber]['name'];
                    }else{
                        $useraddress =preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9-]#u','',$useraddress);
                    }
                    $name = $name_obj->getName();
                    $accountinfo= $this->randomaccount($postdata['agestarttime'],$postdata['ageendtime'],$name);
                    $accountinfo['username']= implode('',$pinyin->name($name));
                    if(!empty($addressdata[$cmulativeNumber]['name'])) {
                        if (empty($insertvalues)) {
                            $insertvalues = "(" . $memberinfo['t_id'] . ",'" . $accountinfo['username'].$accountinfo['eamil'].C('EAMILSERVICES')[array_rand(C('EAMILSERVICES'),1)] . "','" . $postdata['userdefaultpwd'] . "','" . $v . "','" . $accountinfo['birthday'] . "','" . $accountinfo['username'].$accountinfo['eamil'] . "','" . $remark . "', '" . $name . "','".$u_city['province']."','". $postdata['addresscode']."','2','".$useraddress . $postdata['featurs']."','1')";
                        } else {
                            $insertvalues .= ",(" . $memberinfo['t_id'] . ",'" . $accountinfo['username'].$accountinfo['eamil'].C('EAMILSERVICES')[array_rand(C('EAMILSERVICES'),1)] . "','" . $postdata['userdefaultpwd'] . "','" . $v . "','" . $accountinfo['birthday'] . "','" . $accountinfo['username'].$accountinfo['eamil'] . "','" . $remark . "', '" . $name . "','".$u_city['province']."','". $postdata['addresscode']."','2','".$useraddress . $postdata['featurs']."','1')";
                        }
                    }
                    $cmulativeNumber++;
                }
                unset($ponedata,$accountinfo,$resultaddressdata,$addressdata,$name);
                $insertsql = "insert into f_user (t_id,u_eamil,u_pwd,mobile,birthday,u_name,u_field,firstname,u_city,u_addresscode,u_create_type,u_address,u_status) values " . $insertvalues . " ";
                unset($insertvalues);
                $usermodel = M('user', 'f_', C('flashSale'));
                $resultcount = $usermodel->execute($insertsql);
                if($resultcount>0) {
                    $string = "成功导入" . $resultcount . "个用户";
                    $this->ajaxSuccess($string);
                }else{
                    $string = "批量失败";
                    $this->ajaxError($string);
                }
                exit;
            }
            $Model = M('','',C('flashSale'));
            $teamsql="select * from f_team where t_id='".$memberinfo['t_id']."' ";
            $resulttean=$Model->query($teamsql);
            $resulttean[0]['adressmindate'] = floor((time()-strtotime($resulttean[0]['adressmindate']))/86400/360);
            $resulttean[0]['adressmaxdate'] = floor((time()-strtotime($resulttean[0]['adressmaxdate']))/86400/360);
            $this->assign('team_info',$resulttean[0]);
            $this->display();
            exit;
        }
        echo "非法请求";
    }


    /**
     * @efect:创建抢购任务
     * @auth:leishaofa
     * @date:20170928
    */
    public function timeTaskAdd(){
        if(IS_POST){
            $memberinfo = session('member_info');
            $taskid=$_GET['id'];
            $starttime=$_POST['tasktime'];
            //调用python脚本获取商品属性
            $postData = array('pythontype' => 'Timer', 'name' =>'startTask.py' , 'time' =>$starttime);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            $output = curl_exec($ch);
            curl_close($ch);
            if (preg_match('/^\xEF\xBB\xBF/', $output)) {
                $output = substr($output, 3);
            }
            $output = json_decode(trim($output), true);
            $array = $output['data'];
            $ret = $output['status'];
            if ($ret == 1) {
                $model = M('', '', C('flashSale'));
                $sql="select task_relid from f_task_rel where task_type=3 and rules like '%\"taskrelid\":\"".$taskid."\"%'";
                $result=$model->query($sql);
                if(!empty($result)){
                    $attr=array('python'=>'1','taskrelid'=>$taskid);
                    $addsql="INSERT INTO f_task_rel (task_id,t_id,rules,status,task_type,createtime,site_id) VALUES(0,".$memberinfo['t_id'].",'".json_encode($attr,JSON_UNESCAPED_UNICODE)."',1,3,$starttime,0) ";
                    $result =  $model->execute($addsql);
                    if($result){
                        $this->ajaxSuccess("任务添加成功");
                    }else{
                        $this->ajaxError("任务添加失败");
                    }
                }else{
                    $this->ajaxError("任务已经创建，定时任务列表查看");
                }
            }
            if ($ret == 2) {
                $this->ajaxError("pythonerror:".$array);
            } else {
                /* print_r();
                     exit;
                 $attr=json_decode($array[0],true);*/
                // $allsize=htmlentities(htmlspecialchars_decode($attr['allSize']));
                $dao['goods_attr'] = json_encode(json_decode($array[0], true));
            }
        }
        $this->display();
    }

    /**
     * @efect:批量解锁用户
     * @auth:leishaofa
     * @date:2017-10-11
    */
    public function unlock(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $model=M('','',C('flashSale'));
            $cardresult=$model->execute("update f_user_remark set re_status =0 where re_status = 1 and t_id='".$memberinfo['t_id']."' ");
            $sql="update f_user as a inner join f_user_rel as d on a.u_id=d.u_id set d.u_site_task_status=1 where a.t_id =".$memberinfo['t_id']." AND d.u_site_task_status = 2";
            $result=$model->execute($sql);
            $uid=$model->query("select group_concat(a.u_id) as uidcat from f_user as a INNER JOIN f_user_rel as b on a.u_id=b.u_id where b.u_site_status=0 and a.t_id =".$memberinfo['t_id']." ");
         //  var_dump("select group_concat(a.u_id) as uidcat from f_user as a INNER JOIN f_user_rel as b on a.u_id=b.u_id where b.u_site_status=0 and a.t_id =".$memberinfo['t_id']."");
            if($uid){ $model->execute("delete from f_user_rel where u_id in (".$uid[0]['uidcat'].") and u_site_status = 0 "); }
            if($result || $cardresult){
                $model->execute("update f_user_remark set re_status =0 where re_status = 1 and t_id='".$memberinfo['t_id']."' ");
                $this->ajaxSuccess("成功",$result);
            }else{
                $this->ajaxError("没有可释放的");
            }
        }
    }

    /**
     * @efect:检测账户
     * @auth:leishaofa
     * @date:2017-10-20
    */
    public function checkaccount(){
        if(IS_AJAX){
            $memberinfo=session('member_info');
            $model=M('user', 'f_', C('flashSale'));
            $sql='SELECT a.u_id,a.u_eamil,a.u_pwd FROM f_user AS a INNER JOIN f_user_rel AS d ON a.u_id = d.u_id WHERE a.t_id = '.$memberinfo['t_id'].' and d.u_site_status = 3 limit 5';
            $result=$model->query($sql);
            if(is_array($result)) {
                $securess=0;
                $seerror=0;
                foreach ($result as $key=>$val){
                    $postData = array('pythontype' => 'checkaccount', 'eamil' => $val['u_eamil'], 'pwd' => $val['u_pwd'],'u_id'=>$val['u_id']);
                    $cmh=curl_multi_init();
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                    curl_multi_add_handle($cmh, $ch);
                    curl_multi_exec($cmh, $active);
                    $output = curl_exec($ch);
                    curl_close($ch);
                    if (preg_match('/^\xEF\xBB\xBF/', $output)) {
                        $output = substr($output, 3);
                    }
                    $output = json_decode(trim($output), true);
                    $array = $output['data'];
                    $ret = $output['status'];
                    if(is_array($array) && $array[0]==1){
                        M('','',C('flashSale'))->execute("update f_user_rel set u_site_status=1 where t_id =".$memberinfo['t_id']." AND u_id = 2");
                        $securess++;
                    }else{
                        $seerror++;
                    }
                }
                $this->ajaxSuccess("失效用户登陆成功".$securess."个用户"."登陆失败".$seerror."个用户");
            }else{
                $this->ajaxError("你的账号很健康,没有可检测账号");
            }
        }
    }

    /**
     * 用户信息库
    */
    public function remarkUser(){
        $memberinfo=session('member_info');
        $model=M('', '', C('flashSale'));
        if(IS_AJAX){
            $page=is_numeric($_GET['p'])?$_GET['p']:0;
            if(empty($page)){
                $this->ajaxError("页码错误");
            }
            $startnumber=($page-1)*C('PAGENUMBER');
            $where='';
            $sqlcount = "select a.*,IFNULL(b.u_eamil,' ')as u_eamil,IFNULL(b.u_pwd,' ') as u_pwd from f_user_remark as a left join f_user as b on a.u_id=b.u_id where  a.t_id ='".$memberinfo['t_id']."' " . $where . " limit ".$startnumber." , ".C('PAGENUMBER')." ";
            $this->ajaxSuccess("成功" ,$model->query($sqlcount));
        }
        $resultcount=$model->query('select count(1) as counts from f_user_remark where t_id ='.$memberinfo['t_id'].' ');
        $this->assign('page',ceil($resultcount[0]['counts']/C('PAGENUMBER')));
        $this->display();
    }

    /**
     * excel导入新的用户地址信息库
    */
    public function remarkUserAdd(){
        if(IS_AJAX){
            if(!empty(IS_POST)){
                $memberinfo=session('member_info');
                $model=M('', '', C('flashSale'));
                $data=json_decode($_POST['data'],true);
                $insertvalues='';
                foreach ($data as $k=>$v) {
                    //验证身份证号
                    if(checkIdCard($v['cardid'])) {
                            $insertvalues[$v['cardid']] = "(" . $memberinfo['t_id'] . ",'" . $v['cardid'] . "','" . $v['cardname'] . "','" . $v['privce'] . "','" . $v['city'] . "','" . $v['district'] . "','')";
                    }
                }
                if(is_array($insertvalues)) {
                    $insertkey = array_keys($insertvalues);//获取所有过滤后的身份证号码
                    $insertkey = $model->query('select u_card_id from f_user_remark where t_id =' . $memberinfo['t_id'] . ' and u_card_id in (' . implode(',', $insertkey) . ')');
                    //查询数据库是否存在，存在去掉
                    if($insertkey) {
                        $ids = array_unique(array_column($insertkey, 'u_card_id'));
                        /* array_filter($insertvalues,function($val) use ($ids){
                             return in_array($val[''],$ids);
                         });*/
                        foreach ($insertvalues as $key => $val) {
                            if (in_array($key, $ids)) {
                                unset($insertvalues[$key]);
                            }
                        }
                    }
                    $insertvalues = array_values($insertvalues);
                    if(is_array($insertvalues)) {
                        $insertvalues = implode(',', $insertvalues);
                    }
                    $sql="insert into f_user_remark (t_id,u_card_id,u_card_name,u_privace,u_city,district,u_id) VALUES $insertvalues";
                    $number=$model->execute($sql);
                    if($number){
                        $this->ajaxSuccess("导入".$number."个信息成功,已被占用".count($ids)."个用户,其他身份证号码不合法");
                    }else{
                        $this->ajaxError("导入失败用户信息全部以被占用");
                    }
                }
                $this->ajaxError("没有合法的身份证号码");
            }
            $this->display();
        }
    }

}